package com.imist.nettybasic4.server.handler;

import com.imist.nettybasic4.protocol.request.GroupMessageRequestPacket;
import com.imist.nettybasic4.protocol.request.MessageRequestPacket;
import com.imist.nettybasic4.protocol.response.GroupMessageResponsePacket;
import com.imist.nettybasic4.protocol.response.MessageResponsePacket;
import com.imist.nettybasic4.session.Session;
import com.imist.nettybasic4.utils.SessionUtils;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;

@ChannelHandler.Sharable
public class GroupMessageRequestHandler extends SimpleChannelInboundHandler<GroupMessageRequestPacket> {
    public static final GroupMessageRequestHandler INSTANCE = new GroupMessageRequestHandler();

    protected GroupMessageRequestHandler() {
    }
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupMessageRequestPacket groupMessageRequestPacket) throws Exception {
        // 1.拿到群消息，构造群消息的响应;
        String groupId = groupMessageRequestPacket.getToGroupId();

        GroupMessageResponsePacket groupMessageResponsePacket = new GroupMessageResponsePacket();
        groupMessageResponsePacket.setFromGroupId(groupId);
        groupMessageResponsePacket.setMessage(groupMessageRequestPacket.getMessage());
        //拿到当前的用户session
        groupMessageResponsePacket.setFromUser(SessionUtils.getSession(ctx.channel()));

        // 2.拿到群聊对应的channelGroup，写到每个客户端
        ChannelGroup channels = SessionUtils.getChannelGroup(groupId);
        channels.writeAndFlush(groupMessageResponsePacket);
    }
}
